
const validate = require('../middleware/validator')
const { body } = require('express-validator')
const User = require('../models/user')
const bcrypt = require('bcryptjs')
const response = require('../utils/response')


// 用户登录
exports.login = [
    validate([
        body('workerNumber')
        .notEmpty().withMessage('用户名不能为空'),
        body('password')
        .notEmpty().withMessage('密码不能为空')
    ]),
    validate([
        body('workerNumber')
        .custom(async (workerNumber, { req } ) => {
            const user = await User.findOne({workerNumber})
            if(!user){
                return Promise.reject('用户名不存在')
            }
            req.user = user
        })
    ]),
    validate([
        body('password')
        .custom(async (password, { req } ) => {
            let isEqual = await bcrypt.compare(password, req.user.password)
            if (!isEqual) return Promise.reject('密码错误')
        })
    ])
]

// 用户修改信息
exports.updatedUser = [
    validate([

    ]),
    async(req,res,next) => {
        const userId = req.params.userId
        let user = await User.findById(userId)
        if (!user) return response(res,401,'用户不存在~~',null)
        req.user = user
        next()
    }
]

// 用户修改密码
exports.updatedPws = [
    validate([
        body('old_password')
        .notEmpty().withMessage('旧密码不能为空~~'),
        body('new_password')
        .notEmpty().withMessage('新密码不能为空~~'),
    ]),
    async(req,res,next) => {
        const userId = req.params.userId
        let user = await User.findById(userId).lean()
        if (!user) return response(res,401,'用户不存在~~',null)
        req.user = user
        next()
    }
]


// 用户注册
// exports.register = validate([
//     body('user.username')
//     .notEmpty().withMessage('用户名不能为空')
//     .custom(async username => {
//         const user = await User.findOne({username})
//         if(user){
//             return Promise.reject('用户名已存在')
//         }
//     }),

//     body('user.password')
//     .notEmpty().withMessage('密码不能为空'),

//     body('user.email')
//     .notEmpty().withMessage('邮箱不能为空')
//     .isEmail().withMessage('邮箱格式不正确')
//     .custom(async email => {
//         const user = await User.findOne({email})
//         if(user){
//             return Promise.reject('邮箱已存在')
//         }
//     })
      
// ])